<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2022/1/25
 * Time: 10:45
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Stock extends Base
{
    /**
     * 库存列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $bg_name = input('bg_name');
            $bar_code = input('bar_code');
            $where = [];
            if(isset($bg_name) && $bg_name != ''){
                $where['bg_name'] = ['like', '%' . $bg_name . '%'];
            }
            if(isset($bar_code) && $bar_code != ''){
                $where['gs_bar_code'] = ['like', '%' . $bar_code . '%'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 100;
            $count = Db::name('goods_stock')
                ->join('up_bo_goods', 'gs_goods_id = bg_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('goods_stock')
                ->join('up_bo_goods', 'gs_goods_id = bg_id', 'LEFT')
                ->where($where)
                ->field('gs_id, bg_name, gs_bar_code')
                ->order('gs_id desc')
                ->page($Nowpage,$limits)
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 导入Excel
     * @return mixed
     */
    public function excelIn(){
        set_time_limit(0);
        if(request()->file('file')){
            $bg_id  = input('bg_id');
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $data = [];
            for ($i=2; $i<=$highestRow; $i++) {
                $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue ();//获取A列的值
                if($a){
                    $data[$i] = [
                        'gs_goods_id' => $bg_id,
                        'gs_bar_code' => $a,
                        'gs_id' => $a,
                        'gs_time' => date('Y-m-d H:i:s')
                    ];
                }

            }
            Db::table('up_goods_stock')->insertAll($data, true);
            echo '/admin/stock/index';
        }
            
        $goods = Db::table('up_bo_goods')->where('bg_status', 1)->field('bg_id, bg_name, bg_spec')->select();
        return $this->fetch('stock/excelin', ['goods' => $goods]);
    }
    
    /**
     * 录入产品码
     * @return mixed|\think\response\Json
     */
    public function barCodeAdd(){
        if(Request::instance()->isPost()){
            $gs_goods_id = input('gs_goods_id');
            $code = input('code');
            $type = input('type') ? input('type') : 1;

            if(!$gs_goods_id) return json(['code' => 100, 'msg' => '请选择产品']);
            if(!$code) return json(['code' => 100, 'msg' => '请录入防伪码']);

            $bar_code = explode("\n", $code);
            $bar_code = array_filter($bar_code); // 去掉空数组
            $bar_code = array_unique($bar_code); // 去重

            $goods = Db::table('up_bo_goods')->where('bg_id', $gs_goods_id)->field('bg_product_code')->find();
            if(!$goods['bg_product_code']) return json(['code' => 100, 'msg' => '请先设置商品产品码']);
            
            $stock = Db::table('up_goods_stock')->where('gs_bar_code', $goods['bg_product_code'])->find();

            $insert = [];
            $have = '';
            foreach($bar_code as $k => $v){
                $fw = Db::table('up_goods_stock_info')->where('fw_code', $v)->find();
                if($fw){
                    $have .= $v . ',';
                }
                $insert[$k] = [
                    'fw_code' => $v,
                    'goods_id' => $gs_goods_id,
                    'time' => date('Y-m-d H:i:s'),
                    'type' => $type
                ];
            }
            if($have){
                $have = rtrim($have, ',');
                return json(['code' => 100, 'msg' => $have . '防伪码已入库']);
            }

            Db::startTrans();
            try{
                // 入库
                if(!$stock){
                    $gs_id = Db::table('up_goods_stock')->insertGetId([
                        'gs_goods_id' => $gs_goods_id,
                        'gs_bar_code' => $goods['bg_product_code'],
                        'gs_time' => date('Y-m-d H:i:s')
                    ]);
                }else{
                    $gs_id = $stock['gs_id'];
                }

                // 防伪码
                foreach($bar_code as $kk => $vv){
                    $insert[$kk]['stock_id'] = $gs_id;
                }
                Db::table('up_goods_stock_info')->insertAll($insert);

                Db::commit();
                return json(['code' => 200, 'msg' => '录入成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getLine() . ':' . $e->getMessage()]);
            }
        }
        $goods = Db::table('up_bo_goods')->where('bg_status', 1)->field('bg_id, bg_name, bg_spec')->select();
        return $this->fetch('stock/barcodeadd', ['goods' => $goods]);
    }

    /**
     * 编辑产品码
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function productUpdate(){
        $gs_id = input('gs_id');
        if(Request::instance()->isPost()){
            $gs_bar_code = input('gs_bar_code');

            $res = Db::table('up_goods_stock')->update([
                'gs_id' => $gs_id,
                'gs_bar_code' => $gs_bar_code
            ]);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $code = Db::table('up_goods_stock')->where('gs_id', $gs_id)->value('gs_bar_code');
        return $this->fetch('', ['code' => $code, 'gs_id' => $gs_id]);
    }

    /**
     * 防伪码
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fWCode(){
        if(request()->isAjax ()){
            $fw_code = input('fw_code');
            $where['stock_id'] = session('gs_id');
            if($fw_code){
                $where['fw_code'] = ['LIKE', '%' . $fw_code . '%'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 100;
            $count = Db::name('goods_stock_info')->where($where)->count();// 获取总条数
            $lists = Db::name('goods_stock_info')
                ->where($where)
                ->field('id, fw_code, type, time')
                ->page($Nowpage,$limits)
                ->order('time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $gs_id = input('gs_id');
        if($gs_id){
            session('gs_id', $gs_id);
        }
        return $this->fetch('stock/fwcode');
    }

    /**
     * 删除防伪码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function fWDel(){
        $id = input('id');
        $res = Db::table('up_goods_stock_info')->delete($id);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

}